package com.neuedu.it.teach.controller;

import com.neuedu.it.teach.controller.vo.OrderDetailVO;
import com.neuedu.it.teach.controller.vo.Result;
import com.neuedu.it.teach.entity.Help;
import com.neuedu.it.teach.entity.OrderStatus;
import com.neuedu.it.teach.service.HelpService;
import com.neuedu.it.teach.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/*TODO: 要做增查改，
    增就是插入一条数据
    查分为查询全部的订单，还有获取自己的订单信息，
    改要分为，修改teacher_confirmed，修改parent_confirmed，俩个接口，每次修改都得判断对方改没改，双方都改了就修改时间
    删除没有

* -- 3. 订单状态表（记录老师接单和双方完成确认）
DROP TABLE IF EXISTS `order_status`;
CREATE TABLE `order_status` (
  `order_id` INT NOT NULL AUTO_INCREMENT,
  `help_id` INT NOT NULL,                    -- 关联家长发布的互助信息
  `teacher_id` INT NOT NULL,                 -- 接单的教师ID
  `teacher_confirmed` BOOLEAN DEFAULT FALSE, -- 教师确认完成标志
  `parent_confirmed` BOOLEAN DEFAULT FALSE,  -- 家长确认完成标志
  `teacher_accept_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP, -- 接单时间
  `completed_at` TIMESTAMP NULL,             -- 完成确认时间（双方均确认完成后更新）
  PRIMARY KEY (`order_id`),
  FOREIGN KEY (`help_id`) REFERENCES `mutual_help`(`help_id`) ON DELETE CASCADE,
  FOREIGN KEY (`teacher_id`) REFERENCES `users`(`user_id`) ON DELETE CASCADE
) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4;
*/

@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private HelpService helpService;

    // 1. 新增订单

    @PostMapping("/create")
    public Result createOrder(@RequestBody OrderStatus order) {
        try {

            OrderStatus result = orderService.createOrder(order);
            if(result!=null){
                //修改mutual_help表的状态为in_progress
                System.out.println("订单号："+order.getHelpId());
                helpService.updateHelp(order.getHelpId(), "in_progress");
            }
            return Result.success(result);
        } catch (Exception e) {
            return Result.serverError("创建订单失败: " + e.getMessage());
        }
    }

    // 2. 查询所有订单
    @GetMapping("/all")
    public Result getAllOrders() {
        try {
            return Result.success(orderService.getAllOrders());
        } catch (Exception e) {
            return Result.serverError("查询失败: " + e.getMessage());
        }
    }


    // 查询订单：根据 teacherId、helpId 或 userId（三选一）
    @GetMapping("/byUser")
    public Result<List<OrderDetailVO>> getOrdersByUser(@RequestParam(required = false) Integer teacherId,
                                                       @RequestParam(required = false) Integer helpId,
                                                       @RequestParam(required = false) Integer userId) {
        int count = 0;
        if (teacherId != null) count++;
        if (helpId != null) count++;
        if (userId != null) count++;

        if (count == 0) {
            return Result.badRequest("请传入 teacherId、helpId 或 userId 之一");
        }
        if (count > 1) {
            return Result.badRequest("只能传入一个参数，不能多个参数同时传");
        }

        try {
            List<OrderDetailVO> orders;
            if (teacherId != null) {
                orders = orderService.getOrdersByUser(teacherId, null, null);
            } else if (helpId != null) {
                orders = orderService.getOrdersByUser(null, helpId, null);
            } else {
                orders = orderService.getOrdersByUser(null, null, userId);
            }
            return Result.success(orders);
        } catch (Exception e) {
            return Result.serverError("查询失败: " + e.getMessage());
        }
    }


    // 4. 教师确认完成
    @PostMapping("/teacherConfirm/{orderId}")
    public Result<OrderStatus> teacherConfirm(@PathVariable int orderId) {
        try {
            return Result.success(orderService.updateTeacherConfirmed(orderId));
        } catch (RuntimeException e) {
            return Result.notFound(e.getMessage());
        } catch (Exception e) {
            return Result.serverError("确认失败: " + e.getMessage());
        }
    }

    // 5. 家长确认完成
    @PostMapping("/parentConfirm/{orderId}")
    public Result<OrderStatus> parentConfirm(@PathVariable int orderId) {
        try {
            return Result.success(orderService.updateParentConfirmed(orderId));
        } catch (RuntimeException e) {
            return Result.notFound(e.getMessage());
        } catch (Exception e) {
            return Result.serverError("确认失败: " + e.getMessage());
        }
    }

    @DeleteMapping("/del/{orderId}")
    public Result deleteOrder(@PathVariable int orderId) {
        int rows = orderService.deleteOrderById(orderId);
        if (rows > 0) {
            return Result.success("删除成功");
        } else {
            return Result.badRequest("订单不存在或删除失败");
        }
    }


}
